package cn.zhz.springdoc.console.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.zhz.springdoc.console.mapper.IOpenApiMapper;
import cn.zhz.springdoc.console.po.OpenApiPo;
import cn.zhz.springdoc.core.dto.ApiPushDto;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import static cn.zhz.springdoc.core.constant.SpringDocConstant.PUSH_API_OK;
import static cn.zhz.springdoc.core.constant.SpringDocConstant.PUSH_API_URL;

/**
 * @author ZHZ
 * @since 2022-11-15
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class ApiPushController {

    private final IOpenApiMapper iOpenApiMapper;

    @PostMapping(PUSH_API_URL)
    public String docs(@RequestBody ApiPushDto apiPushDto) {

        log.info("接收到推送信息：{}", JSONUtil.toJsonStr(apiPushDto));
        OpenApiPo openApiPo = iOpenApiMapper.selectOne(Wrappers.lambdaQuery(OpenApiPo.class)
                .eq(OpenApiPo::getGroupName, apiPushDto.getGroupName())
                .eq(OpenApiPo::getProjectName, apiPushDto.getProjectName()));

        if (openApiPo == null) {
            OpenApiPo openApi = BeanUtil.copyProperties(apiPushDto, OpenApiPo.class);
            iOpenApiMapper.insert(openApi);
        } else {
            openApiPo.setOpenApiJson(apiPushDto.getOpenApiJson());
            openApiPo.setVersion(apiPushDto.getVersion());
            iOpenApiMapper.updateById(openApiPo);
        }
        return PUSH_API_OK;
    }
}
